package com.sntk.organauthomanager.application.mapper;

import com.sntk.organauthomanager.application.dto.UserDTO;
import com.sntk.organauthomanager.application.dto.UserVO;
import com.sntk.organauthomanager.infrastructure.db.entity.OrganizationEntity;
import com.sntk.organauthomanager.infrastructure.db.entity.UserEntity;
import com.sntk.organauthomanager.infrastructure.db.repository.OrganizationDBRepository;
import com.sntk.organauthomanager.infrastructure.db.repository.UserDBRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @ClassName: UserMapper
 * @author: wgchao
 * @createTime: 2020/7/21 9:22 AM
 * @Description: TODO
 */
@Component
public class UserMapper {
    @Autowired
    private OrganizationDBRepository organizationDBRepository;
    @Autowired
    private UserDBRepository userDBRepository;

    public UserDTO transformToDTO(UserEntity userEntity){
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userEntity, userDTO);
        return userDTO;
    }

    public UserVO transformToVO(UserEntity userEntity){
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userEntity, userVO);
        if(!StringUtils.isEmpty(userEntity.getInstitutionNumber())){
            OrganizationEntity organization = organizationDBRepository.findFirstByInstitutionNumberAndDelFalse(userEntity.getInstitutionNumber());
            if(organization != null){
                userVO.setInstitutionName(organization.getInstitutionName());
            }
        }
        if(!StringUtils.isEmpty(userEntity.getCreator())){
            UserEntity creator = userDBRepository.findFirstByUnameAndDelFalse(userEntity.getCreator());
            if(creator != null){
                userVO.setCreatorName(creator.getUserName());
            }
        }
        if(!StringUtils.isEmpty(userEntity.getLastUpdator())){
            UserEntity updator = userDBRepository.findFirstByUnameAndDelFalse(userEntity.getLastUpdator());
            if(updator != null){
                userVO.setLastUpdatorName(updator.getUserName());
            }
        }

        return userVO;
    }
}
